package com.xspace.android.imcommon.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.util.Log;

import com.xspace.android.imcommon.entity.ChatMsg;

import java.util.ArrayList;

/**
 * MessageDb数据库
 * 
 * @author pc-1
 * 
 */
public class MessageDb extends BaseDb {

	private static final int EXPIRE_LIMIT = 10 * 10000 * 10000;// 过期数据限制为10万条

	public MessageDb(Context context) {
		super(context);
	}

	public static final String TAG = "MessageDb";

	/**
	 * _id
	 */
	public static final String _ID = "_id";
	/**
	 * 内容
	 */
	public static final String COLOUMN_CONTENT = "content";
	/**
	 * 最新内容类型 0：文本 1、图片 2、语音 3、视频
	 */
	public static final String COLOUMN_CONTENT_TYPE = "content_type";
	/**
	 * 消息发送时间
	 */
	public static final String COLOUMN_SEND_TIME = "send_time";
	/**
	 * 插入时间
	 */
	public static final String COLOUMN_INSERT_TIME = "insert_time";
	/**
	 * 消息状态 0：发送中 1:发送成功 2 发送失败,3 接收
	 */
	public static final String COLOUMN_STATUS = "status";
	/**
	 * 消息状态 0：未读 1:已读
	 */
	public static final String COLOUMN_READ = "read";
	/**
	 * 发送消息的barejid 接收者
	 */
	public static final String COLOUMN_BAREJID = "barejid";
	/**
	 * 发送消息的uuid
	 */
	public static final String COLOUMN_UUID = "uuid";
	/**
	 * 推送消息所属人 发送者
	 */
	public static final String COLOUMN_OWNER = "owner";
	public static final String COLOUMN_From_UserName = "from_user_name";
	public static final String COLOUMN_From_UserLogo = "from_user_logo";
	public static final String COLOUMN_To_UserName = "to_user_name";
	/**
	 * 错误码
	 */
	public static final String COLOUMN_ERRORCODE = "errorCode";
	/**
	 * 错误消息
	 */
	public static final String COLOUMN_ERRORMSG = "errorMsg";
	public static final String TABLE_NAME = "CHAT_MSG";
	/**
	 * 图片本地存储路径
	 */
	public static final String COLOUMN_IMGPATH = "imgPath";
	public static final String CREATE_TABLE =  "CREATE TABLE " + TABLE_NAME + " (" + _ID + " INTEGER primary key, " + COLOUMN_CONTENT
			+ " CHAR(1000)," + COLOUMN_CONTENT_TYPE + " INTEGER," + COLOUMN_SEND_TIME + " CHAR(128),"
			+ COLOUMN_INSERT_TIME + " CHAR(128)," + COLOUMN_STATUS + " INTEGER," + COLOUMN_READ + " INTEGER,"
			+ COLOUMN_BAREJID + " CHAR(128)," + COLOUMN_UUID + " CHAR(128), " + COLOUMN_OWNER + " CHAR(128),"
			+ COLOUMN_From_UserName + " CHAR(128),"+ COLOUMN_To_UserName + " CHAR(128),"+ COLOUMN_From_UserLogo + " CHAR(128),"
			+ COLOUMN_ERRORCODE + " CHAR(128)," + COLOUMN_ERRORMSG + " CHAR(128)," + COLOUMN_IMGPATH + " CHAR(128))";

	@Override
	String getTableName() {
		return TABLE_NAME;
	}

	/**
	 * 保存消息数据
	 * 
	 * @param city
	 * @return
	 */
	public int insertOrUpdateMsg(ChatMsg chatMsgBean) {
		Log.d(TAG, "insertOrUpdateMsg()... received message: " + chatMsgBean);

		ContentValues values = new ContentValues();
		values.put(COLOUMN_BAREJID, chatMsgBean.toUser);
		values.put(COLOUMN_CONTENT, chatMsgBean.mContent);
		values.put(COLOUMN_CONTENT_TYPE, chatMsgBean.mContentType);
		values.put(COLOUMN_INSERT_TIME, chatMsgBean.mInsertTime);
		values.put(COLOUMN_OWNER, chatMsgBean.fromUser);
		values.put(COLOUMN_SEND_TIME, chatMsgBean.mSendTime);
		values.put(COLOUMN_STATUS, chatMsgBean.mStatus);
		values.put(COLOUMN_READ, chatMsgBean.mRead);
		values.put(COLOUMN_UUID, chatMsgBean.mUUID);
		values.put(COLOUMN_ERRORCODE, chatMsgBean.errorCode);
		values.put(COLOUMN_ERRORMSG, chatMsgBean.errorMsg);
		values.put(COLOUMN_IMGPATH, chatMsgBean.imgPath);
		values.put(COLOUMN_From_UserName, chatMsgBean.fromUserName);
		values.put(COLOUMN_To_UserName, chatMsgBean.mToUserName);
		values.put(COLOUMN_From_UserLogo, chatMsgBean.fromUserLogo);
		System.out.println("------------------------chatMsgBean.fromUser:"+chatMsgBean.fromUser);
		String sql = "select * from " + TABLE_NAME + " where " + COLOUMN_SEND_TIME + " = '" + chatMsgBean.mSendTime + "'";
		Cursor cursor = null;
		try {
			long rowId = -1;
			checkDb();
			cursor = db.rawQuery(sql, null);
			if (cursor != null && cursor.getCount() > 0) {
				rowId = db.update(TABLE_NAME, values, COLOUMN_SEND_TIME  + "=?", new String[] { chatMsgBean.mSendTime });
			} else {
				rowId = db.insert(TABLE_NAME, null, values);
				Log.e(TAG, "insertOrUpdateMsg()... insert rowId: " + rowId);
			}
			return (int) rowId;
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		} finally {
			closeDbAndCursor(cursor);
		}
	}

	// 修改信息状态
	public boolean updateMsg(ChatMsg chatMsgBean) {
		try {
			checkDb();
			ContentValues values = new ContentValues();
			values.put(COLOUMN_BAREJID, chatMsgBean.toUser);
			values.put(COLOUMN_CONTENT, chatMsgBean.mContent);
			values.put(COLOUMN_CONTENT_TYPE, chatMsgBean.mContentType);
			values.put(COLOUMN_INSERT_TIME, chatMsgBean.mInsertTime);
			values.put(COLOUMN_OWNER, chatMsgBean.fromUser);
			values.put(COLOUMN_SEND_TIME, chatMsgBean.mSendTime);
			values.put(COLOUMN_STATUS, chatMsgBean.mStatus);
			values.put(COLOUMN_READ, chatMsgBean.mRead);
			values.put(COLOUMN_UUID, chatMsgBean.mUUID);
			values.put(COLOUMN_ERRORCODE, chatMsgBean.errorCode);
			values.put(COLOUMN_ERRORMSG, chatMsgBean.errorMsg);
			values.put(COLOUMN_IMGPATH, chatMsgBean.imgPath);
			values.put(COLOUMN_From_UserName, chatMsgBean.fromUserName);
			values.put(COLOUMN_To_UserName, chatMsgBean.mToUserName);
			values.put(COLOUMN_From_UserLogo, chatMsgBean.fromUserLogo);
			int num = db.update(TABLE_NAME, values, COLOUMN_SEND_TIME + "=?", new String[] { chatMsgBean.mSendTime + "" });
			Log.d(TAG, "updateByfddHouse_id data effected number:" + num);
			return (num > 0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	// 修改信息状态
	public boolean updateMsgState(String fromUserId) {
		try {
			checkDb();
			ContentValues cv = new ContentValues();
			cv.put(COLOUMN_STATUS, 2);
			int num = db.update(TABLE_NAME, cv, COLOUMN_STATUS + "=? and " + COLOUMN_BAREJID + "=?", new String[] { 1 + "", fromUserId });
			Log.d(TAG, "updateByfddHouse_id data effected number:" + num);
			return (num > 0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 
	 * @Description: 查询每组聊天消息列表
	 * @param barejid
	 * @param owner
	 * @return
	 * @throws
	 */
	public ArrayList<ChatMsg> queryChatMsgs(String barejid, String owner) {
		ArrayList<ChatMsg> chatMsgs = new ArrayList<ChatMsg>();
			String sql = "select * from " + TABLE_NAME + " where " +COLOUMN_OWNER + "='" + owner + "' and "
					+ COLOUMN_BAREJID + "='" + barejid + "' order by "+_ID + " desc";
			Log.d(TAG, "queryChatMsgs()... " + sql);
			System.out.println("------------------------sql:"+sql);
			Cursor cursor = null;
			try {
				checkDb();
				cursor = db.rawQuery(sql, null);
				if (cursor != null && cursor.getCount() > 0) {
					cursor.moveToLast();
					for (int i = cursor.getCount() - 1; i >= 0; i--) {
						cursor.moveToPosition(i);
						ChatMsg entity = parseCursor(cursor);
						chatMsgs.add(entity);
					}
				}
			return chatMsgs;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			} finally {
				closeDbAndCursor(cursor);
			}
	}


	private ChatMsg parseCursor(Cursor cursor) {
		ChatMsg chatMsg = new ChatMsg();
		chatMsg._id = cursor.getInt(cursor.getColumnIndex(_ID));
		chatMsg.toUser = cursor.getString(cursor.getColumnIndex(COLOUMN_BAREJID));
		chatMsg.mContent = cursor.getString(cursor.getColumnIndex(COLOUMN_CONTENT));
		chatMsg.mContentType = cursor.getInt(cursor.getColumnIndex(COLOUMN_CONTENT_TYPE));
		chatMsg.mInsertTime = cursor.getString(cursor.getColumnIndex(COLOUMN_INSERT_TIME));
		chatMsg.fromUser = cursor.getString(cursor.getColumnIndex(COLOUMN_OWNER));
		chatMsg.mSendTime = cursor.getString(cursor.getColumnIndex(COLOUMN_SEND_TIME));
		chatMsg.mStatus = cursor.getInt(cursor.getColumnIndex(COLOUMN_STATUS));
		chatMsg.mRead = cursor.getInt(cursor.getColumnIndex(COLOUMN_READ));
		chatMsg.mUUID = cursor.getString(cursor.getColumnIndex(COLOUMN_UUID));
		chatMsg.errorCode = cursor.getString(cursor.getColumnIndex(COLOUMN_ERRORCODE));
		chatMsg.errorMsg = cursor.getString(cursor.getColumnIndex(COLOUMN_ERRORMSG));
		chatMsg.imgPath = cursor.getString(cursor.getColumnIndex(COLOUMN_IMGPATH));
		chatMsg.fromUserLogo = cursor.getString(cursor.getColumnIndex(COLOUMN_From_UserLogo));
		chatMsg.fromUserName = cursor.getString(cursor.getColumnIndex(COLOUMN_From_UserName));
		chatMsg.mToUserName = cursor.getString(cursor.getColumnIndex(COLOUMN_To_UserName));
		return chatMsg;
	}
	
	public ChatMsg queryChatMsgById(int msgId) {
			String sql = "select * from " + TABLE_NAME + " where _ID=" + msgId;
			Cursor cursor = null;
			try {
				checkDb();
				cursor = db.rawQuery(sql, null);
				if (cursor != null && cursor.getCount() > 0) {
					cursor.moveToLast();
						cursor.moveToPosition(0);
					   return parseCursor(cursor);
				}
				else{
					return null;
				}
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			} finally {
				closeDbAndCursor(cursor);
			}
	}

	/**
	 * 查找信息是否存在
	 * 
	 * @param state
	 * @return
	 */
	public boolean findMsg(String sendMsgId) {
		String sql = "select * from " + TABLE_NAME + " where " + COLOUMN_SEND_TIME + " ='" + sendMsgId + "'";
		Log.d(TAG, "findMsg()... " + sql);
		Cursor cursor = null;
		try {
			checkDb();
			cursor = db.rawQuery(sql, null);
			return (cursor != null && cursor.getCount() > 0);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeDbAndCursor(cursor);
		}
		return false;
	}

	public void clearAllData() {
		try {
			checkDb();
			String sql = "delete from " + TABLE_NAME + ";";
			db.execSQL(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public boolean clearExpireData() {
		int count = getCount();
		Cursor cursor = null;
		try {
			if (count > EXPIRE_LIMIT) {
				checkDb();

				String sql = "delete from " + TABLE_NAME + " where _id in (select _id from " + TABLE_NAME + " order by _id asc limit 0," + (count - EXPIRE_LIMIT) + ")";
				Log.d(TAG, "clearExpireData()... messages is exceed the limit, and execute " + sql);

				cursor = db.rawQuery(sql, null);
				return (cursor != null && cursor.getCount() > 0);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			closeDbAndCursor(cursor);
		}
		Log.d(TAG, "clearExpireData()... messages is not exceed the limit ");

		return false;
	}

	private int getCount() {
		String sql = "select count(*) from " + TABLE_NAME;
		Log.d(TAG, "getCount()... " + sql);
		Cursor cursor = null;
		try {
			checkDb();
			cursor = db.rawQuery(sql, null);
			if (cursor != null && cursor.getCount() > 0) {
				cursor.moveToFirst();
				return cursor.getInt(0);
			} else {
				return 0;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			closeDbAndCursor(cursor);
		}
		return 0;
	}
	public boolean deleteMsg(String userId, String fromUserId) {
		try {
			checkDb();
			String whereClause = String.format(" %s = ? and %s = ? ", COLOUMN_BAREJID, COLOUMN_OWNER);
			String[] whereArgs = new String[] { userId, fromUserId };
			int res = db.delete(TABLE_NAME, whereClause, whereArgs);
			return res > 0;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}
	public boolean deleteMsg(int msgId) {
		try {
			checkDb();
			String whereClause = String.format(" %s = ?", "_ID");
			String[] whereArgs = new String[] {""+msgId};
			int res = db.delete(TABLE_NAME, whereClause, whereArgs);
			return res >= 0;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

}
